package com.mmall.service;

import com.google.common.base.Preconditions;
import com.mmall.Exception.ParamException;
import com.mmall.dao.SysUserMapper;
import com.mmall.model.SysUser;
import com.mmall.param.UserParam;
import com.mmall.util.BeanBalidator;
import com.mmall.util.MD5Util;
import com.mmall.util.PasswordUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * Created by pc on 2019/4/2.
 */
@Service
public class SysUserService {
    @Resource
    private SysUserMapper sysUserMapper;

    public void save(UserParam param){
        BeanBalidator.check(param);
        if(checkTelephoneExist(param.getTelephone(),param.getId())){
            throw new ParamException("电话已被占用");
        }
        if(checkEmailExist(param.getMail(),param.getId())){
            throw new ParamException("邮箱已被占用");
        }

        String password = PasswordUtil.randomPassword();
        password = "12345678";
        String encryptedPassword = MD5Util.encrypt(password);
        SysUser user = new SysUser();
        BeanUtils.copyProperties(param,user);
        user.setOperator("system");
        user.setOperateIp("127.0.0.1");
        user.setOperateTime(new Date());
        user.setPassword(encryptedPassword);
        //TODO: sendEmial

        sysUserMapper.insertSelective(user);
    }

    public void update(UserParam param){
        BeanBalidator.check(param);
        if(checkTelephoneExist(param.getTelephone(),param.getId())){
            throw new ParamException("电话已被占用");
        }
        if(checkEmailExist(param.getMail(),param.getId())){
            throw new ParamException("邮箱已被占用");
        }
        SysUser before = sysUserMapper.selectByPrimaryKey(param.getId());
        Preconditions.checkNotNull(before,"待更新的用户不存在");

        SysUser after = new SysUser();
        BeanUtils.copyProperties(param,after);
        after.setOperator("system");
        after.setOperateIp("127.0.0.1");
        after.setOperateTime(new Date());
       sysUserMapper.updateByPrimaryKeySelective(after);
    }

    public boolean checkEmailExist(String mail,Integer userId){
        return false;
    }

    public boolean checkTelephoneExist(String phone,Integer userId){
        return false;
    }

    public SysUser findByKeyword(String keyword){
        return sysUserMapper.findByKeyword(keyword);
    }
}
